package com.lcb.redis;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

/****
 * @Author:刘长柏
 * @Date: 2021-01-20 11:01
 * @Description:springboot整合redis
 *****/
@RestController
public class IndexController {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 测试主节点挂了,哨兵重新选举新的节点,客户端能否动态感知到,客户端动态切换访问的master ip
     *
     * @throws InterruptedException
     */
    @GetMapping("/testSentinel")
    public void testSentinel() throws InterruptedException {
        int i = 1;
        while (true) {
            try {
                stringRedisTemplate.opsForValue().set("lcb" + i, i + "");
                System.out.println("设置key:" + "lcb" + i);
                i++;
                Thread.sleep(1000);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 测试主节点挂了,哨兵重新选举新的节点,客户端能否动态感知到,客户端动态切换访问的master ip
     *
     * @throws InterruptedException
     */
    @GetMapping("/testCluster")
    public String testCluster() throws InterruptedException {
        stringRedisTemplate.opsForValue().set("lcb", "高兴啊");

        String lcb = stringRedisTemplate.opsForValue().get("lcb");

        return lcb;
    }
}
